var utils = require('../../../utils/utils.js');
var latitude = 0, longitude = 0;
var PX = 0.0056, PY = -0.00228;
var task = [], taskNum = 0;
var nowTaskInfo = '';
var nowTask = {}; // 当前任务
var refreshTimes = 0;
Page({
  data: {
    latitude: 0, 
    longitude: 0,
    task_la:0,  
    task_lo:0, 
    polyline: [], 
    markers: [],
    nowTask: '正在查询任务',
    greeting:'正在查询任务',
    loc_name: '',
    taskNum: 0,
    disabled: true,
  },

  getTask: function(e) {
    var that = this;
    wx.req('attendanceTaskInfoGet', { user_id: wx.appData.user_id }).then((res) => {
      console.log({ user_id: wx.appData.user_id })
      wx.req('attendanceHistoryGet', { user_id: wx.appData.user_id }).then((history) => {
        console.log(res.odr, res.data)
        taskNum = res.data.data.length - history.data.data.length;
        // for (var i = 0; i < res.data.data.length; i++)
        //   if (res.data.data[i].ifSuccess == true) taskNum--;
        that.setData({
          greeting: '今天还有' + taskNum + '项任务',
          taskNum: taskNum
        })
      })
    })
  }, 
  // 
  getDistance(lat1, lng1, lat2, lng2) {
    var radLat1 = lat1 * (Math.PI / 180), radLat2 = lat2 * (Math.PI / 180);
    var a = radLat1 - radLat2, b = lng1 * (Math.PI / 180) - lng2 * (Math.PI / 180);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
      Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137 * 1000; // 返回单位：m  
    //s=s.toFixed(2);
    return s;
  },
  //点击考勤
  click: function(e) {
    var that = this,
    locName = '',
    now = utils.formatDate(Date.parse(new Date()), 'time');
    console.log(now)
    that.setData({ disabled: true });
    that.getTask();
    wx.getLocation({
      success(res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
        });
        var d = that.getDistance(res.latitude, res.longitude, nowTask.lat, nowTask.lon);
        console.log('距离圆心（米）：', d)
        if (d < 100) {
          var AHA_data = {
            user_id: wx.appData.user_id,
            task_info_id: nowTaskInfo,
            lon: that.data.longitude,
            lat: that.data.latitude
          }
          wx.req('attendanceHistoryAdd', AHA_data, '请稍候').then((res) => {
            console.log(res.odr, res.data);
            wx.modal('考勤成功', '您在' + res.data.data[i].name + '考勤成功。');
            that.setData({ disabled: false });
          })
        } else {
          wx.modal('考勤不成功', '请确认您是否在指定位置范围内。');
          that.setData({ disabled: false });
        }
        
      },
      fail(fail) {
        wx.showToast({
          image: '/assets/fail.png',
          title: '刷新失败，请检查定位是否开启'
        });
        that.setData({ disabled: false });
      },
    })
  },

  // 加载当日任务
  onShow: function () {
    if (!refreshTimes) return 0;  // 若 onLoad 未完成则不开始 onShow 
    var that = this;
    wx.req('attendanceTaskInfoGet', { user_id: wx.appData.user_id }, '查询中').then((res) => {
      console.log({ user_id: wx.appData.user_id })
      console.log(res.odr, res.data);
      task = res.data.data || [];
      var list = [];
      wx.req('locationGet', {}, '正在获取地点').then((res) => {
        wx.req('attendanceHistoryGet', { user_id: wx.appData.user_id }).then((history) => {
          console.log(history.odr, history.data)
          console.log(res.odr, res.data)
          var r = res.data.data;
          wx.getLocation({
            success: function (wxLoc) {
              that.setData({
                latitude: wxLoc.latitude,
                longitude: wxLoc.longitude,
                show_latitude: wxLoc.latitude + PY,
                show_longitude: wxLoc.longitude + PX,
              });
              for (var i = 0; r && i < r.length; i++)
                list.push({
                  location_id: r[i].location_id,
                  task_id: r[i].task_id,
                  time: r[i].start_time,
                  id: i,
                  img: "",
                  name: r[i].name,
                  info: '经度' + r[i].lon + ', 纬度' + r[i].lat,
                  lo: r[i].lon,
                  la: r[i].lat,
                });
              wx.appData.loc = list;
              var trash = task;
              task = [];
              for (var i = 0; i < trash.length; i++)
                for (var j = 0; j < wx.appData.loc.length; j++)
                  if (trash[i].location_id == wx.appData.loc[j].location_id) {
                    that.createPoints(trash, i, j);
                    break;
                  }
              if (that.data.nowTask == '正在查询任务')
                that.setData({
                  nowTask: '当前无考勤任务',
                  disabled: true
                });
              console.log('今日任务数组', task);
              that.getTask();
              // wx.navigateTo({ url: '/pages/admin/admin/admin' })
            },
          })
        })
      }).catch((res) => {
        console.log(res);
        wx.showModal({
          title: '查询地址位置失败',
          content: '无法连接到服务器。\n您已登录成功，但尚未获取任务位置信息。',
          showCancel: false,
          confirmText: '重新查询',
          success(confirm) { 
            if (confirm.confirm) that.onShow();
           
          }
        });
      });
    }).catch((res) => {
      wx.hideLoading()
      wx.showModal({
        title: '查询任务失败',
        content: '无法连接到服务器。\n注意：您现在尚未获取任务。',
        showCancel: false,
        confirmText: '重新查询',
        success(confirm) {if (confirm.confirm) that.onShow(); }
      })
    })
  },
  // 构造当前任务点
  createPoints: function (trash, i, j) {
    var that = this;
    // var taskTime = utils.catchTime({
    //   hour: trash[i].time.h,
    //   minute: trash[i].time.m,
    //   second: trash[i].time.s
    // });
    var taskTime = trash[i].start_time;
    task.push({
      id: wx.appData.loc[j].id,
      info: wx.appData.loc[j].location_id,
      img: wx.appData.loc[j].img,
      name: wx.appData.loc[j].name,
      lo: wx.appData.loc[j].lo,
      la: wx.appData.loc[j].la,
      time: taskTime,
    });
    if (that.data.nowTask == '正在查询任务') {
      var h = trash[i].start_time.split(':')[0];
      var m = trash[i].start_time.split(':')[1];
      nowTaskInfo = '';
      if (utils.compareTime(parseInt(h), parseInt(m))) {
        console.log('当前任务是', trash[i]);
        nowTask = trash[i];
        nowTaskInfo = trash[i].task_info_id;
        var oneCircle = [], onePolyline = [], markers = [];
        onePolyline.push({
          longitude: parseFloat(wx.appData.loc[j].lo) + PX,
          latitude: parseFloat(wx.appData.loc[j].la) + PY
        }, {
          longitude: parseFloat(that.data.longitude) + PX,
          latitude: parseFloat(that.data.latitude) + PY
        });
        markers.push({
          iconPath: '../../img/mapicon_navi_s.png',
          id: 0,
          title: '当前任务',
          latitude: parseFloat(wx.appData.loc[j].la) + PY,
          longitude: parseFloat(wx.appData.loc[j].lo) + PX,
          callout: {
            content: wx.appData.loc[j].name,
            borderRadius: 10,
            padding: 10,
            borderWidth: 1,
            borderColor: '#66d1ff',
            display: 'BYCLICK',
            textAlign: 'center',
          }
        });
        oneCircle.push({
          latitude: parseFloat(wx.appData.loc[j].la) + PY,
          longitude: parseFloat(wx.appData.loc[j].lo) + PX,
          //latitude:  that.data.latitude,
          //longitude: that.data.longitude,
          color: '#00aa2199',
          fillColor: '#00ff4111',
          radius: 100,
        });
        that.setData({
          nowTask: taskTime + '\n' + wx.appData.loc[j].name,
          disabled: false,
          circles: oneCircle,
          markers: markers,
          polyline: [{
            points: onePolyline,
            color: "#0091ff",
            width: 2
          }],
        });
      }
    }

  },

  //页面加载时，先登录账户。
  onLoad: function (op) {
    refreshTimes = 0;
    var that = this
    wx.showLoading({ title: '登录中', mask: true })
    wx.login({
      success: function (res) {
        var UL_data = { code: res.code }
        that.setData({ loginCode: res.code })
        console.log(res)
        // wx.hideLoading()
        // return;
        wx.req('userLogin', UL_data, '准备用户信息').then((res) => {
          wx.appData.PHPSESSID = 'PHPSESSID=' + res.data.PHPSESSID;
          console.log(res.odr, res)
          if (res.data.errCode == 4002 || res.data.errCode == 4004)
            wx.modal('请先认证', '您尚未认证个人信息。', '', '前往认证').then(() => {
              wx.navigateTo({ url: '/pages/my/register/register' });
            })
          else {
            wx.appData.openid = res.data.data.openid;
            wx.appData.user_id = res.data.data.user_id;
            refreshTimes++; // 刷新次数记为一次
            that.onShow();
          }
        })
      },
      fail: function (res) {
        wx.hideLoading()
        wx.modal(
          '登录账户失败',
          '请检查网络状况或账号安全状况。\n您现在处于未登录状态。',
          '', '重新登录'
        ).then(() => { that.onShow() })
      }
    })
  }, 

  getLoc: function () {
    var that = this
    wx.getLocation({
      type: 'wgs84', //返回可以用于wx.openLocation的经纬度
      success(res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
        });
        wx.request({ // 百度地图API，将微信获得的经纬度传给百度，获得城市等信息
          url: 'https://api.map.baidu.com/geocoder/v2/?ak=GAKrXdS2lPhNejYKnvfalheyoiTqcnWG&location=' + res.latitude + ',' + res.longitude + '&output=json&coordtype=wgs84ll',

          header: { 'Content-Type': 'application/json' },
          success: function (f) { that.setData({ loc_name: f.data.result.sematic_description }) },
          fail: function () { wx.toast('获取位置信息失败！') },
        })
        if (refreshTimes) { wx.toast('刷新成功', 'success') }; refreshTimes++;
      },
      fail(res) { wx.toast('刷新失败，请检查定位是否开启') }
    })
  },
  onShareAppMessage: function () {

  }
})